// pages/Goods/GoodsClassify/GoodsClassify.js
//获取应用实例
const app = getApp();
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryGoodsLists , updateShoppingCartGoods } from '../../../api/goods';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    item: {},
    cateName: '',
    grade: '',
    colorId: '',
    goodsList: [], // 商品列表
    gradeList: [], // 等级列表
    colorList: [], // 颜色列表
    goodsName: '',
    assetsAddress: assetsAddress,
    shopCartItem: {},
    show: false,
    quantity: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    wx.setNavigationBarTitle({
      title: JSON.parse(options.cateParentName),
    })
    this.setData({
      item: JSON.parse(options.item),
      cateName: JSON.parse(options.cateName),
    })
    this._queryGoodsLists();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  _queryGoodsLists(){
    let _this = this;
    queryGoodsLists({cateId: _this.data.item.cateId,storehouseId: _this.data.item.storehouseId,areaId: _this.data.item.areaId,goodsId: _this.data.item.goodsId,grade: _this.data.grade,colorId: _this.data.colorId,size: 99,goodsName: _this.data.goodsName})
    .then(res => {
      if(res.success){
        _this.setData({
          goodsList: res.data.content,
        })
        if(res.data.content.length > 0){
          if(_this.data.grade == '' && _this.data.colorId == ''){
            var gradeList = [];
            gradeList.push(res.data.content[0].grade);
            var colorList = [];
            colorList.push({
              'colorId': res.data.content[0].colorId,
              'colorName': res.data.content[0].colorName
            })
            for (let index = 0; index < res.data.content.length; index++) {
              const item = res.data.content[index];
              if(!gradeList.find(grade => grade == item.grade)){
                gradeList.push(item.grade);
              }
              if(!colorList.find(color => color.colorId == item.colorId)){
                colorList.push({
                  'colorId': item.colorId,
                  'colorName': item.colorName
                })
              }
            }
            _this.setData({
              colorList: colorList,
              gradeList: gradeList,
            })
          }
        }
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 输入框发生变化
  onSearchChange(e) {
    this.setData({
      goodsName: e.detail,
    });
  },
  // 输入框搜索
  onSearch(){
    this._queryGoodsLists();
  },
  // 选择颜色
  setColor(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item);
    this.setData({
      colorId: item,
    })
    this._queryGoodsLists();
  },
  setGrade(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item);
    this.setData({
      grade: item,
    })
    this._queryGoodsLists();
  },
  // 跳转商品详情
  goDetail(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    console.log(item,'goodsClassifyItem');
    wx.navigateTo({
      url: `${url}?item=${JSON.stringify(this.data.item)}&colorId=${JSON.stringify(item.colorId)}&grade=${JSON.stringify(item.grade)}&description=${encodeURIComponent(item.description)}&remarks=${encodeURIComponent(item.remarks)}&id=${item.id}&merchantId=${item.merchantId}`,
    })
  },
  // 展示购物车商品
  addShopCart(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item.isClosed == '1'){
      wx.showToast({
        title: '当前商品已打烊，请更换其他商品',
        icon: 'none',
      });
      return;
    }
    console.log(item);
    this.setData({
      shopCartItem: JSON.parse(JSON.stringify(item)),
      show: true,
    })
  },
  onClose(){
    this.setData({
      show: false,
    })
  },
  onChange(event) {
    this.setData({
      quantity: event.detail,
    })
  },
  addShopCartSubmit(){
    let _this = this;
    var shoppingCartId = wx.getStorageSync('shoppingCartId') ? wx.getStorageSync('shoppingCartId') : '';
    updateShoppingCartGoods({goodsDetailsId: _this.data.shopCartItem.id,isSelect: '1',id: shoppingCartId,quantity: _this.data.quantity})
    .then(res => {
      if(res.success){
        _this.setData({
          show: false
        })
        wx.showToast({
          title: '已成功加入购物车',
          icon: 'none',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
})